<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before>
          共{{ total }}条记录
        </template>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportToExcel">导出</el-button>
          <el-button size="small" type="primary" @click="isShowDialog">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeesList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <!-- 头像 -->
          <el-table-column label="头像" sortable="" width="200px">
            <template v-slot="{row}">
              <img v-fixUrl="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="staffPhoto" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatterEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="{row}">
              <!-- {{ new Date(row.timeOfEntry).toLocaleDateString() }} -->
              <!-- 管道符"|" -->
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template #default="{row}">
              <!-- el-switch中v-model绑定的是一个布尔值 可以使用active-value（激活）inactive-value（未激活）可以替换默认绑定的布尔值 -->
              <el-switch
                v-model="row.enableState"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="btnRole(row.id)">角色</el-button>
              <el-button v-if="checkPrem('delUser')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageEmployees.size" @current-change="currentChange" />
        </el-row>
      </el-card>
    </div>
    <AddEmployee ref="fromData" :show-dialog.sync="showDialog" @addEmployee="addEmployeeFn" />
    <el-dialog :visible="isShowCode" title="二维码" @close="isShowCode = false">
      <el-row type="flex" justify="center">
        <canvas ref="qrcode" />
      </el-row>
    </el-dialog>

    <AssignRole ref="formData" :show-role-dialog.sync="showRoleDialog" @roleOk="roleOkFN" />
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import EmployeeEnum from '@/api/constant/employees'
import { delEmployee, getEmployeesList } from '@/api/employee'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    AddEmployee, AssignRole
  },
  // filters: {
  //   formatDate(oldVal) {
  //     return oldVal.split('T')[0]
  //   }
  // },
  data() {
    return {
      pageEmployees: {
        page: 1, // 显示第一页
        size: 5// 每页显示的条数
      },
      total: 0,
      employeesList: [], // 员工列表
      showDialog: false,
      isShowCode: false,
      showRoleDialog: false
    }
  },
  async created() {
    this.getEmployeesList()
  },
  methods: {
    roleOkFN() {
      this.getEmployeesList()
    },
    async  btnRole(id) {
      await this.$refs.formData.getUserDetialByid(id)
      this.showRoleDialog = true
      // console.log(id)
    },
    showCode(imgUrl) {
      this.isShowCode = true
      // 显示弹出框的时候，页面还没有渲染完，此时不能获取到 this.$refs.qrcode
      // 可以使用最粗鲁的办法加定时器，或者使用 nextTict 来解决
      this.$nextTick(() => {
        //  QRCode.toCanvas(拿到dom, 要生成的二维码)
        QRCode.toCanvas(this.$refs.qrcode, imgUrl, { width: 300 })
      })
    },
    // 导出
    async exportToExcel() {
      const { rows } = await getEmployeesList({ page: 1, size: 5 })
      // console.log(rows)
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // Object.keys(对象) 可以得到一个一对象的key 组成数组
      // header 中文的key
      const header = Object.keys(dict)
      const data = rows.map(item => {
        return this.objToArr(item, dict)
      })
      // console.log(data)
      await export_json_to_excel({
        header, // header:deader
        data// data:data
      })
    },
    objToArr(userObj, dict) {
      // userObj 当前对象
      const newUser = []
      // 转换逻辑
      for (const key in dict) {
        // 因为要拿到key的值（此时的key是中文，需要先转为为英文，然后在拿对应的值）
        const enKey = dict[key]
        // 找到对应的value 放到 newUser 的数组中
        // value 是当前对象的所有key对应的值
        const value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          // 聘用形式
          const obj = EmployeeEnum.hireType.find(item => Number(item.id) === Number(value))
          newUser.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 日期
          newUser.push(value ? formatDate(value) : '')
        } else {
          newUser.push(value)
        }
      }
      // console.log('value值', newUser)
      return newUser
    },
    formatterEmployment(row, col, cell, index) {
      // 枚举：就是把所有可能的东西举例出来，一个一个的列举出来
      // const hireType = [
      //   { id: 1, value: '正式' },
      //   { id: 2, value: '非正式' }
      // ]
      const obj = EmployeeEnum.hireType.find(item => Number(item.id) === (cell))
      return obj?.value
    },
    // 更新数据（父传子）
    addEmployeeFn() {
      this.getEmployeesList()
    },
    // // 查看
    // checkEmployee(id) {
    //   this.showDialog = true
    //   this.$refs.fromData.getCheckEmployee(id)
    // },
    // 显示/隐藏
    isShowDialog() {
      this.showDialog = true
    },
    // 根据id删除用户信息
    async delEmployee(id) {
      await this.$confirm('你确定要删除吗？')
      await delEmployee(id)
      this.$message.success('删除成功')
      this.getEmployeesList()
    },
    // 页数跳转
    currentChange(newPage) {
      this.pageEmployees.page = newPage
      this.getEmployeesList()
    },
    // 员工信息列表
    async getEmployeesList() {
      const { rows, total } = await getEmployeesList(this.pageEmployees)
      this.employeesList = rows
      this.total = total
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 180px;
  height: 120px;
  object-fit: cover;
}
</style>
